import React, { PureComponent } from 'react';
import { Table, Select, InputNumber, Icon, Upload, Button, message, Input, Tooltip } from 'antd';

import { uploadUrl } from '../../../config';
function messageAlert(params) {
  message.destroy();
  message.warning(params)
}
const { Option } = Select;
class ProductSku extends PureComponent {
  state = {
    uploading: false,
    marketPrice: ' ',
    salePrice: ' '
  };

  render() {
    const { value, onChange, buyOutValue, buyOutSupport, editType } = this.props;
    const { uploading } = this.state;
    // 限制用户上传大小与格式
    const beforeUpload = file => {
      const isJPG =
        file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      if (!isJPG) {
        message.error('图片格式不正确');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大于2MB');
      }
      return isJPG && isLt2M;
    };

    const handleChange = (key, v) => {
      if (key == 'marketPrice') {
        if (typeof (v) === 'string' && v != '') messageAlert('请输入正确格式~');
        this.setState({
          marketPrice: v
        }, () => {
          const { marketPrice, salePrice } = this.state;
          if (marketPrice * 1.35 < Number(salePrice) && salePrice != ' ' && marketPrice != ' ') messageAlert('销售价已超上限，请认真填写！');
        })
      } else if (key == 'salePrice') {
        if (typeof (v) === 'string' && v != '') messageAlert('请输入正确格式~');
        this.setState({
          salePrice: v
        }, () => {
          const { marketPrice, salePrice } = this.state;
          if (marketPrice * 1.35 < Number(salePrice) && salePrice != ' ' && marketPrice != ' ') messageAlert('销售价已超上限，请认真填写！');
        })
      }
      const newValue = { ...value };
      newValue[key] = Number(v);
      onChange(newValue);
    };

    const handleChangeUpload = info => {
      if (info.file.status === 'uploading') {
        this.setState({ uploading: true });
        return;
      }
      if (info.file.status === 'done') {
        const newValue = { ...value };
        if (info.file.response.code === 1) {
          newValue.specImage = info.file.response.data;
        } else {
          message.error('上传失败，请重试');
        }
        this.setState({ uploading: false });
        onChange(newValue);
      }
    };

    const handleChangeCycs = v => {
      const newValue = { ...value };
      newValue.cycs = [...value.cycs];
      newValue.cycs.push({
        days: v,
        price: '0.01',
      });
      newValue.cycs = newValue.cycs.sort((a, b) => Number(a.days) - Number(b.days));
      onChange(newValue);
    };

    const handleChangeCycPrice = (v, index) => {
      const newValue = { ...value };
      newValue.cycs = [...value.cycs];
      newValue.cycs[index] = { ...value.cycs[index] };
      newValue.cycs[index].price = v;
      onChange(newValue);
    };

    const handleDeleteCyc = days => {
      const newValue = { ...value };
      newValue.cycs = [...value.cycs];
      const index = newValue.cycs.findIndex(cyc => cyc.days === days);
      if (index > -1) {
        newValue.cycs.splice(index, 1);
      }
      onChange(newValue);
    };
    const textContent = '商家须认真设置销售价格，销售价格需<=市场价*1.35，租户在租期中，买断价格=销售价格-累计支付的租金'
    const TitleContent = (
      <span>
        销售价
        <em style={{ color: '#fff', paddingLeft: 8 }}>
          <Tooltip
            title={
              <div style={{ color: '#fff' }}>
                {textContent}
              </div>
            }
          >
            <Icon type="info-circle-o" style={{ marginRight: 4, color: 'red' }} />
          </Tooltip>
        </em>
      </span>
    )
    const columnses = [
      {
        title: '规格',
        dataIndex: 'spec',
        align: 'center',
        render: (_, record) =>
          !!record.specAll.length &&
          record.specAll.map((spec, index) => (
            <span key={spec.platformSpecId}>
              {spec.platformSpecValue}
              {index + 1 < record.specAll.length && '/'}
            </span>
          )),
      },
      {
        title: '新旧',
        dataIndex: 'oldNewDegree',
        width: 180,
        render: text => {
          return (
            <Select
              value={text}
              placeholder="请选择新旧"
              onChange={v => handleChange('oldNewDegree', v)}
            >
              <Option value={1}>全新</Option>
              <Option value={2}>99新</Option>
              <Option value={3}>95新</Option>
              <Option value={4}>9成新</Option>
              <Option value={5}>8成新</Option>
              <Option value={6}>7成新</Option>
            </Select>
          );
        },
      },
      {
        title: '市场价',
        dataIndex: 'marketPrice',
        width: 180,
        render: text => {
          return (
            <span>
              <InputNumber
                min={0.01}
                precision={2}
                value={text}
                onChange={v => handleChange('marketPrice', v)}
              />{' '}
              元
            </span>
          );
        },
      },
      {
        title: '库存',
        dataIndex: 'inventory',
        width: 180,
        render: text => {
          return (
            <span>
              <InputNumber
                min={0}
                precision={0}
                value={text}
                onChange={v => handleChange('inventory', v)}
              />
            </span>
          );
        },
      },
      {
        title: () => {
          return <span>{TitleContent}</span>
        },
        dataIndex: 'salePrice',
        width: 180,
        render: text => {
          return (
            <span>
              {/* <Input
                // value={text}
                onChange={e => handleChange('salePrice', e.target.value)}
              /> */}
              <InputNumber
                value={text}
                onChange={v => handleChange('salePrice', v)}
              />
            </span>
          );
        },
      },
      {
        title: 'SKU图片',
        dataIndex: 'specImage',
        render: text => (
          <Upload
            accept="image/*"
            action={uploadUrl}
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChangeUpload}
          >
            {text ? (
              <img src={text} alt="avatar" style={{ width: '80px', height: '80px' }} />
            ) : (
                <Button type="primary">
                  <Icon type={uploading ? 'loading' : 'upload'} /> 上传
                </Button>
              )}
          </Upload>
        ),
      },
    ];
    const columns = [
      {
        title: '规格',
        dataIndex: 'spec',
        align: 'center',
        render: (_, record) =>
          !!record.specAll.length &&
          record.specAll.map((spec, index) => (
            <span key={spec.platformSpecId}>
              {spec.platformSpecValue}
              {index + 1 < record.specAll.length && '/'}
            </span>
          )),
      },
      {
        title: '新旧',
        dataIndex: 'oldNewDegree',
        width: 180,
        render: text => {
          return (
            <Select
              value={text}
              placeholder="请选择新旧"
              onChange={v => handleChange('oldNewDegree', v)}
            >
              <Option value={1}>全新</Option>
              <Option value={2}>99新</Option>
              <Option value={3}>95新</Option>
              <Option value={4}>9成新</Option>
              <Option value={5}>8成新</Option>
              <Option value={6}>7成新</Option>
            </Select>
          );
        },
      },
      {
        title: '市场价',
        dataIndex: 'marketPrice',
        width: 180,
        render: text => {
          return (
            <span>
              <InputNumber
                min={0.01}
                precision={2}
                value={text}
                onChange={v => handleChange('marketPrice', v)}
              />{' '}
              元
            </span>
          );
        },
      },
      {
        title: '库存',
        dataIndex: 'inventory',
        width: 180,
        render: text => {
          return (
            <span>
              <InputNumber
                min={0}
                precision={0}
                value={text}
                onChange={v => handleChange('inventory', v)}
              />
            </span>
          );
        },
      },
      {
        title: 'SKU图片',
        dataIndex: 'specImage',
        render: text => (
          <Upload
            accept="image/*"
            action={uploadUrl}
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChangeUpload}
          >
            {text ? (
              <img src={text} alt="avatar" style={{ width: '80px', height: '80px' }} />
            ) : (
                <Button type="primary">
                  <Icon type={uploading ? 'loading' : 'upload'} /> 上传
                </Button>
              )}
          </Upload>
        ),
      },
    ];
    const footerCycs = () => {
      const cycsColumns = [
        {
          title: 'price',
          dataIndex: 'price',
          render: (text, _, index) => (
            <span>
              <InputNumber
                size="small"
                min={0.01}
                precision={2}
                value={text}
                style={{ marginRight: 2 }}
                onChange={v => handleChangeCycPrice(v, index)}
              />
              元/日
            </span>
          ),
        },
        {
          title: 'days',
          dataIndex: 'days',
          render: text => `${text}日及以上`,
        },
        {
          title: 'contant',
          render: (_, record) => (
            <span style={{ color: 'red' }}>
              {`${record.days}日及以上，是指租用时长为${record.days}日以上（包含${
                record.days
                }日）每日的租金价格`}
            </span>
          ),
        },
        {
          title: 'action',
          render: (_, record) => (
            <a onClick={() => handleDeleteCyc(record.days)}>
              <Icon type="close-circle" />
            </a>
          ),
        },
      ];
      const { cycs } = value;
      return (
        <div>
          {cycs.length < 6 && (
            <div style={{ marginBottom: '10px' }}>
              <Select
                value={<span style={{ color: '#bfbfbf' }}>请选择租赁天数</span>}
                optionFilterProp="children"
                style={{ width: '30%' }}
                placeholder="请选择租赁天数"
                onChange={handleChangeCycs}
              >
                <Option key="1" value="1" disabled={cycs.findIndex(c => c.days === '1') > -1}>
                  1日及以上
                </Option>
                <Option key="2" value="7" disabled={cycs.findIndex(c => c.days === '7') > -1}>
                  7日及以上
                </Option>
                <Option key="3" value="30" disabled={cycs.findIndex(c => c.days === '30') > -1}>
                  30日及以上
                </Option>
                <Option key="4" value="90" disabled={cycs.findIndex(c => c.days === '90') > -1}>
                  90日及以上
                </Option>
                <Option key="5" value="180" disabled={cycs.findIndex(c => c.days === '180') > -1}>
                  180日及以上
                </Option>
                <Option key="6" value="365" disabled={cycs.findIndex(c => c.days === '365') > -1}>
                  365日及以上
                </Option>
              </Select>
            </div>
          )}
          <Table
            rowKey={record => record.days}
            dataSource={cycs}
            columns={cycsColumns}
            showHeader={false}
            size="small"
            pagination={false}
          />
        </div>
      );
    };
    return (
      <div style={{ marginBottom: '10px' }}>
        {
          editType == 'add' ?
            <Table
              rowKey={record => record.cycs}
              size="middle"
              columns={buyOutValue === 1 ? columnses : columns}
              dataSource={[value]}
              bordered
              pagination={false}
              footer={footerCycs}
            />
            : <Table
              rowKey={record => record.cycs}
              size="middle"
              columns={buyOutValue == 1 ? columnses : columns}
              dataSource={[value]}
              bordered
              pagination={false}
              footer={footerCycs}
            />
        }
      </div>
    );
  }
}
export default ProductSku;
